<?php
/**
 * Description of RegistryModifier
 *
 * @author joona
 */
abstract class Lib_RegistryModifier
{
    protected static $backedUp = false;

    public static function backupApplicationINI()
    {
        if(self::$backedUp) return;
        $dir = dirname(__FILE__).'/../../Source/Config';

        $applicationINI = $dir.'/Application.ini';

        if(file_exists($applicationINI))
        {
            $iniContent = file_get_contents($applicationINI);
            file_put_contents($dir.'/Application.ini.backup',$iniContent);
        }
        else
        {
            $iniContent = file_get_contents("$applicationINI.sample");
            file_put_contents($dir.'/Application.ini',$iniContent);
        }
        self::$backedUp = true;
    }

    public static function modifyApplicationINI($changes)
    {
        if(!self::$backedUp)
            throw new Lib_RegistryModifier_Exception('Cannot modify application.ini before backing it up');

        $dir = dirname(__FILE__).'/../../Source/Config';

        $originals = array();
        $replacements = array();
        foreach ($changes as $original => $new)
        {
            $originals[] = "/$original/";
            $replacements[] = $new;
        }

        $applicationIni = file_get_contents($dir.'/Application.ini');

        file_put_contents(
                $dir.'/Application.ini',
                preg_replace($originals, $replacements, $applicationIni));
    }

    public static function returnOriginalApplicationINI()
    {
        $dir = dirname(__FILE__).'/../../Source/Config';

        $applicationINIBackup = $dir.'/Application.ini.backup';

        if(file_exists($applicationINIBackup))
        {
            $backupContent = file_get_contents($applicationINIBackup);

            file_put_contents($dir.'/Application.ini',$backupContent);
            unlink($dir.'/Application.ini.backup');
        }
        self::$backedUp = false;
    }
}
class Lib_RegistryModifier_Exception extends Exception { }